#include "server.h"
#include "agents.h"

#define CS(mutex) critical_section __cs(mutex)

BEGIN_GOODS_NAMESPACE

// Class CClientAgent 
CClientAgent::CClientAgent () : m_pServer (NULL),
								m_pSock (NULL),
								term_event (true)	// ʼΪźŵ
{
}

CClientAgent::~CClientAgent ()
{
	if (NULL != m_pSock)
	{
		m_pSock->shutdown();
		m_pSock->close ();
		delete m_pSock;
		m_pSock = NULL;
	}

//	term_event.wait();
}

bool CClientAgent::OnAuthorize()
{
	return true;
}

// static
void task_proc CClientAgent::start (void* arg)
{
	CClientAgent* pClient = ((CClientAgent*)arg);
	pClient->term_event.reset();

	if (pClient->OnAuthorize())
		pClient->Run();
	else
	{
#ifdef _DEBUG
		char* login_name = pClient->m_pSock->get_peer_name ();			
		if (NULL != login_name)
		{
			console::message(msg_login|msg_error|msg_time,
			"Authorization of client '%s' failed!\n", login_name);
			
			delete[] login_name;
		}
#endif
	}

	pClient->term_event.signal();
	if (NULL != pClient->m_pServer)
		pClient->m_pServer->RemoveClientAgent(pClient);
}

bool CClientAgent::IsRuning()
{
	return term_event.wait_with_timeout(0);
}

void CClientAgent::ThreadRun ()
{
	if (NULL == task::create(start, this, task::pri_normal, task::small_stack))
	{
		term_event.signal();
		m_pServer->RemoveClientAgent(this);
	}
}

END_GOODS_NAMESPACE
